package com.tieto.user.bean;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.tieto.user.FacesUtil;
import com.tieto.user.model.Role;
import com.tieto.user.model.User;
import com.tieto.user.service.UserService;

@Slf4j
@Component
@Scope("request")
public class RegisterBean {
    @Getter
    @Setter
    private User user = new User();
    @Setter
    @Autowired
    private transient UserService userService;
    @SuppressWarnings("PMD.UnusedPrivateField")
    @Getter
    private Role[] roles = Role.values();
    @Getter
    @Setter
    private String repeatedPassword;

    /**
     * Called when user presses Register button on register.xhtml.
     */
    public String register() {
        return createUser(Role.ROLE_USER);
    }

    /**
     * Called when user presses Add user button on addUser.xhtml.
     */
    public String addUser() {
        return createUser(user.getRole());
    }

    private String createUser(Role role) {
        if (!repeatedPassword.equals(user.getPassword())) {
            showMessage(null, "repeatedPasswordError");
            return null;
        }
        try {
            user.setRole(role);
            userService.create(user);
            user = new User();
        } catch (IllegalArgumentException e) {
            log.debug("Unable to register user: {]", user);
            showMessage(null, "registerError");
            return null;
        }
        return "userSaved";
    }

    /**
     * showMessage is package private to enable overriding in a test case.
     */
    void showMessage(String id, String messageKey) {
        FacesUtil.showMessage(id, messageKey);
    }
}
